import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../views/Layout.vue'
import { Toast } from 'vant'
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)
Vue.use(Toast)

const routes = [
  {
    path: '/login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/article/:id',
    component: () => import('../views/Detail.vue')
  },
  {
    path: '/',
    redirect: '/article',
    component: Layout,
    children: [
      { path: 'article', component: () => import('../views/Article.vue') },
      { path: 'like', component: () => import('../views/Like.vue') },
      { path: 'collect', component: () => import('../views/Collect.vue') },
      { path: 'user', component: () => import('../views/User.vue') }
    ]
  }

]

const router = new VueRouter({
  routes
})
// 前置导航守卫: 特定时机 自动执行
// 跳转前

const whiteList = ['/login', '/register']
router.beforeEach((to, from, next) => {
  // 产品经理告诉你, 游客只能看登录和注册
  // 如果用户已登录 - 直接放行
  // 如果用户未登录 - 去login register - 也要放行
  next()
  const token = getToken()
  if (token) {
    next()
  } else if (whiteList.includes(to.path)) {
    next()
  } else {
    // 如果用户未登录 - 去article user collect like 文章详情 - 不放行
    Toast('请先登录 再访问')
    next('/login')
  }
})

export default router
